"""The architecture model: layers (L0-L4), Website<->CRM ports, table owners, allow-lists. Normative text: docs/CONTRACTS.md.

Changing anything in this file is an architectural decision: it must be reviewed together with docs/CONTRACTS.md.
Mapping rule for LAYERS: the LONGEST matching module prefix wins.
"""

# ------------------------------------------------------------------------------------------------ layers (K1)
# L0 kernel          shared infrastructure; imports nothing above itself
# L1 integrations/data  clients/parsers, the export engine (pure generator), stores/repositories
# L2 domain services    business rules of Website and CRM, integrator/export executor
# L3 web                blueprints, routes, middleware
# L4 composition        application factory, WSGI/CLI entry points, tools
# 'alias'              compatibility aliases (K7): excluded from layering, governed by the alias registry
LAYERS = {
    # --- L0
    'env_loader': 0, 'modules': 0, 'modules.core': 0, 'modules.connector': 0, 'modules.classes': 0,
    'InvestmentWebsite': 0, 'InvestmentWebsite.offers.record_schema': 0,
    # --- L1
    'integrations': 1, 'InvestmentManager.export_engine': 1,
    'InvestmentManager.scheduler_state': 1, 'InvestmentManager.agents_store': 1,
    'InvestmentManager.offers_store': 1,
    'InvestmentManager.crm_clients_store': 1, 'InvestmentManager.foreign_offers_store': 1,
    'InvestmentManager.foreign_offer_validation': 1, 'InvestmentManager.foreign_sync_merge': 1,
    'InvestmentWebsite.services.platform_logger': 1, 'InvestmentWebsite.services.valuation_repository': 1,
    'InvestmentWebsite.offers.connectors': 1,
    # --- L2
    'InvestmentWebsite.services': 2, 'InvestmentWebsite.offers': 2, 'InvestmentWebsite.seo': 2, 'InvestmentWebsite.assets': 2,
    'InvestmentManager.integrator': 2, 'InvestmentManager.foreign_sync': 2, 'InvestmentManager.foreign_sync_sources': 2,
    'InvestmentManager.foreign_sync_actions': 2, 'InvestmentManager.foreign_offers_importer': 2, 'InvestmentManager.leady_pipeline': 2,
    'InvestmentManager.form_config': 2, 'InvestmentManager.offer_cards': 2,
    'InvestmentManager.scrapers': 2, 'InvestmentManager.scheduled_jobs': 2,
    # --- L3
    'InvestmentManager': 3, 'InvestmentManager.routes': 3, 'InvestmentManager.main': 3, 'InvestmentManager._blueprint': 3,
    'InvestmentManager.middleware': 3, 'InvestmentWebsite.blueprints': 3, 'blueprints': 3, 'blueprints.media': 3,
    # --- L4
    'modules.core.app_factory': 4, 'flask_app': 4, 'passenger_wsgi': 4, 'run_local': 4, 'tools': 4,
    'InvestmentManager.export_handoff': 4, 'InvestmentManager.export_engine.__main__': 4, 'InvestmentManager.scrapers.__main__': 4,
}
# Compatibility layer (K7). A module is an alias when its code aliases another module (sys.modules[__name__] = ...) or when it
# lives under one of these packages (package markers and facades such as modules.investment.functions). Every alias must be
# covered by a registry entry (owner, reason, removal criterion); production code must not import aliases.
ALIAS_PREFIXES = ('modules.investment', 'modules.offers', 'modules.tripinvest', 'modules.avarten', 'modules.cyprus_constructions',
                  'modules.homelanzarote', 'modules.assets', 'modules.seo', 'blueprints.avarten', 'blueprints.cyprus',
                  'blueprints.homelanzarote', 'blueprints.investment', 'blueprints.platform', 'blueprints.tripinvest')
_CANON_BP = 'The application factory imports the canonical blueprint (removes the K7 violation); external scripts confirmed.'
ALIAS_REGISTRY = (
    {'prefix': 'modules.investment', 'canonical': 'InvestmentWebsite.services.*', 'owner': 'Website',
     'reason': 'Old import paths of the Website services and the facade modules.investment.functions (declared import contract).',
     'removal': 'No external script imports modules.investment.* (owner confirms) and the 14 tests use the canonical paths.'},
    {'prefix': 'modules.offers', 'canonical': 'InvestmentWebsite.offers.*', 'owner': 'Website',
     'reason': 'Old import paths of the public offers package (declared import contract).',
     'removal': 'No external script imports modules.offers.* (owner confirms) and test_import_contract.py is updated.'},
    {'prefix': 'modules.tripinvest', 'canonical': 'integrations.tripinvest.*', 'owner': 'Integrations',
     'reason': 'Old import paths and CLI entries of the TripInvest integration.',
     'removal': 'External scripts and the old CLI entry are retired by the owner.'},
    {'prefix': 'modules.avarten', 'canonical': 'integrations.avarten.*', 'owner': 'Integrations',
     'reason': 'Old import paths of the Avarten integration.', 'removal': 'External scripts are retired by the owner.'},
    {'prefix': 'modules.cyprus_constructions', 'canonical': 'integrations.cyprus_constructions.*', 'owner': 'Integrations',
     'reason': 'Old import paths and two old CLI entries of the Cyprus Constructions integration.',
     'removal': 'External scripts and the old CLI entries are retired by the owner.'},
    {'prefix': 'modules.homelanzarote', 'canonical': 'integrations.homelanzarote.*', 'owner': 'Integrations',
     'reason': 'Old import path and CLI entry of the Homelanzarote scraper (the old file delegates to the new one).',
     'removal': 'The old CLI entry is retired by the owner.'},
    {'prefix': 'modules.assets', 'canonical': 'InvestmentWebsite.assets', 'owner': 'Website',
     'reason': 'Old path still used by the application factory (migration target: canonical import).',
     'removal': 'The factory imports InvestmentWebsite.assets directly (removes the K7 violation); external scripts confirmed.'},
    {'prefix': 'modules.seo', 'canonical': 'InvestmentWebsite.seo', 'owner': 'Website',
     'reason': 'Old path still used by the application factory (migration target: canonical import).',
     'removal': 'The factory imports InvestmentWebsite.seo directly (removes the K7 violation); external scripts confirmed.'},
    {'prefix': 'blueprints.avarten', 'canonical': 'InvestmentWebsite.blueprints.avarten', 'owner': 'Website',
     'reason': 'Old blueprint path still used by the application factory.', 'removal': _CANON_BP},
    {'prefix': 'blueprints.cyprus', 'canonical': 'InvestmentWebsite.blueprints.cyprus', 'owner': 'Website',
     'reason': 'Old blueprint path still used by the application factory.', 'removal': _CANON_BP},
    {'prefix': 'blueprints.homelanzarote', 'canonical': 'InvestmentWebsite.blueprints.homelanzarote', 'owner': 'Website',
     'reason': 'Old blueprint path still used by the application factory.', 'removal': _CANON_BP},
    {'prefix': 'blueprints.investment', 'canonical': 'InvestmentWebsite.blueprints.investment', 'owner': 'Website',
     'reason': 'Old blueprint path still used by the application factory.', 'removal': _CANON_BP},
    {'prefix': 'blueprints.platform', 'canonical': 'InvestmentWebsite.blueprints.platform', 'owner': 'Website',
     'reason': 'Old blueprint path still used by the application factory.', 'removal': _CANON_BP},
    {'prefix': 'blueprints.tripinvest', 'canonical': 'InvestmentWebsite.blueprints.tripinvest', 'owner': 'Website',
     'reason': 'Old blueprint path still used by the application factory.', 'removal': _CANON_BP},
)

# ------------------------------------------------------------------------------------------------ ports (K2)
# The ONLY allowed imports between the Website (InvestmentWebsite.*) and the CRM (InvestmentManager.*), outside the composition layer.
# (importing module, imported module) -> set of imported names ('*' = the module itself / any name). Each has a documented reason.
PORTS = {
    ('InvestmentManager.routes.offer_catalog', 'InvestmentWebsite.services.catalog'): {
        'names': {'invalidate_offer_caches'},
        'reason': 'CRM drops the Website offer caches after catalog writes (no second copy of the cache).'},
    ('InvestmentWebsite.services.franchise_service', 'InvestmentManager.crm_clients_store'): {
        'names': {'*'},
        'reason': 'The public franchise service stores clients and meetings in the CRM clients store.'},
}

# ------------------------------------------------------------------------------------------------ table owners (K3)
# table -> modules forming the controlled WRITE INTERFACE (one interface may span a few cooperating modules of one domain).
# 'transitional': the interface is today a route module; the target is a repository (see docs/CONTRACTS.md).
OWNERS = {
    'estatedata': {'modules': {'InvestmentManager.routes.offer_catalog'}, 'transitional': True},
    'localization': {'modules': {'InvestmentManager.routes.offer_catalog'}, 'transitional': True},
    'sold': {'modules': {'InvestmentManager.routes.offer_catalog'}, 'transitional': True},
    'agents_v2': {'modules': {'InvestmentManager.agents_store'}},
    'branches_v2': {'modules': {'InvestmentManager.agents_store'}},
    'roles_v2': {'modules': {'InvestmentManager.agents_store'}},
    'agent_branches_v2': {'modules': {'InvestmentManager.agents_store'}},
    'agent_roles_v2': {'modules': {'InvestmentManager.agents_store'}},
    'foreign_sync_runs': {'modules': {'InvestmentManager.foreign_offers_store'}},
    'foreign_offer_raw_snapshots': {'modules': {'InvestmentManager.foreign_offers_importer'}},
    'offer_portal_sync': {'modules': {'InvestmentManager.integrator.portal_sync_state', 'InvestmentManager.integrator.export_attempts',
                                      'InvestmentManager.integrator.input_consistency'}},
    'offer_portal_sync_events': {'modules': {'InvestmentManager.integrator.portal_sync_state'}},
    'foreign_offers': {'modules': {'InvestmentManager.foreign_offers_store'}},
    'foreign_offer_portal_sync': {'modules': {'InvestmentManager.foreign_offers_store', 'InvestmentManager.integrator.foreign_attempt_inputs',
                                              'InvestmentManager.integrator.foreign_consistency'}},
    'foreign_offer_portal_sync_events': {'modules': {'InvestmentManager.foreign_offers_store', 'InvestmentManager.integrator.foreign_consistency'}},
    'foreign_offer_export_warnings': {'modules': {'InvestmentManager.foreign_offer_validation'}},
    'foreign_developments': {'modules': {'InvestmentManager.foreign_sync', 'InvestmentManager.foreign_offers_store'}},
    'foreign_offer_features_raw': {'modules': {'InvestmentManager.foreign_sync', 'InvestmentManager.foreign_offers_store'}},
    'foreign_offer_images': {'modules': {'InvestmentManager.foreign_sync', 'InvestmentManager.foreign_offers_store'}},
    'foreign_offer_sync_log': {'modules': {'InvestmentManager.foreign_sync', 'InvestmentManager.foreign_offers_store'}},
    'crm_clients': {'modules': {'InvestmentManager.crm_clients_store'}},
    'crm_client_offers': {'modules': {'InvestmentManager.crm_clients_store'}},
    'crm_client_meetings': {'modules': {'InvestmentManager.crm_clients_store'}},
    'crm_client_status_history': {'modules': {'InvestmentManager.crm_clients_store'}},
    'crm_client_activity_log': {'modules': {'InvestmentManager.crm_clients_store'}},
    'crm_leads': {'modules': {'InvestmentManager.leady_pipeline'}},
    'crm_lead_events': {'modules': {'InvestmentManager.leady_pipeline'}},
    'lead_inbox': {'modules': {'InvestmentManager.leady_pipeline'}},
    'crm_valuation_leads': {'modules': {'InvestmentWebsite.services.valuation_repository'}},
    'platform_logs': {'modules': {'InvestmentWebsite.services.platform_logger'}},
    'export_jobs': {'modules': {'InvestmentManager.integrator.export_jobs'}},
    'export_job_events': {'modules': {'InvestmentManager.integrator.export_jobs'}},
}

# Tables whose write interface spans several modules need ONE coordinating module that is responsible for the invariants and for the
# transaction boundary of every logical change (the others take part in the coordinator's transaction/lock order instead of committing
# on their own). Coordinators are designated here at stage 0; whether the code already behaves this way is verified in audit part 2.
COORDINATORS = {
    'offer_portal_sync': 'InvestmentManager.integrator.portal_sync_state',
    'foreign_offer_portal_sync': 'InvestmentManager.integrator.foreign_consistency',
    'foreign_offer_portal_sync_events': 'InvestmentManager.integrator.foreign_consistency',
    'foreign_developments': 'InvestmentManager.foreign_sync',
    'foreign_offer_features_raw': 'InvestmentManager.foreign_sync',
    'foreign_offer_images': 'InvestmentManager.foreign_sync',
    'foreign_offer_sync_log': 'InvestmentManager.foreign_sync',
}

# ------------------------------------------------------------------------------------------------ K4 / K5 / K6 scopes
# K4: direct SQL (execute/executemany/executescript, sqlite3.connect) is forbidden in the web layer (L3) - per-file ratchet.
# K5: only these modules may read the process environment; everything else receives settings (arguments / app config).
ENV_READERS = {
    'modules.core.config': 'selects the configuration and reads application settings',
    'modules.core.storage_paths': 'resolves DATA_DIR and the runtime layout (single resolver)',
    'env_loader': 'switches os.environ to UTF-8 before the dotenv load (flask_app/export_handoff)',
    'flask_app': 'loads the production .env before the application factory runs',
    'run_local': 'loads .env.dev for local development',
    'InvestmentManager.integrator.export_transport_config': 'export executor reads its own FTP/company keys (cron does not load .env)',
}

# ------------------------------------------------------------------------------------------------ K9 (export subsystem)
# The pure export engine must not import the rest of the project, Flask or any transport.
ENGINE_PACKAGE = 'InvestmentManager.export_engine'
ENGINE_FORBIDDEN_THIRD_PARTY = {'flask', 'werkzeug', 'ftplib', 'paramiko', 'requests', 'socket'}
# Only the transport module may open FTP connections.
FTP_ALLOWED_MODULES = {'InvestmentManager.integrator.portal_transport'}
# Tests that already enforce the export contracts; docs/CONTRACTS.md lists them and the contract test checks they exist.
K9_EXISTING_TESTS = (
    'tests/investmentmanager/test_integrator_export_engine_removed.py',
    'tests/investmentmanager/test_export_deployment_safety.py',
    'tests/investmentmanager/test_portal_transport.py',
    'tests/investmentmanager/test_queue_characterization.py',
    'tests/investmentmanager/test_export_job_qualification.py',
    'tests/export_generation/test_foreign_contract.py',
)

CONTRACT_IDS = ('K1', 'K2', 'K3', 'K4', 'K5', 'K6', 'K7', 'K8', 'K9')
